/**
 * 图层树方法
 */
import { nextTick } from "vue";
import { store, widget, closeContextMenu, mars3d, graphicLayer, map } from "@/utils/global";
import { ElMessageBox, ElMessage } from "element-plus";
import { addFloader, getCoverage, updateFloaderShow, updateFloaderUp, updateFloaderDown, updateFloaderUpFolder, updateFloaderDownFolder } from "@/api/coverage";
import { uploadXyzLayers } from "@/api/draw";
/**
 * 初始化图层树数据
 */
export const treeDataInit = (data: []) => {
    let tree = store.tree;
    data.forEach((v: any, i: Number) => {
        if (v.show || v.show == "1") {
            nextTick(() => {
                tree.setChecked(v.id, true, true);
                tree.setCurrentKey(store.treeDefaultKey, true);
            });
        }
        if (v.children && v.children.length > 0) {
            treeDataInit(v.children);
        }
    });
};
/**
 * 向树里面添加数据
 */
export const toTreeApendData = (data: []) => {
    let tree = store.tree;
    data.forEach((v: any, i: Number) => {
        let node = newTreeNode(v);
        tree.append(node, v.pid);

        if (node.show) {
            nextTick(() => {
                tree.setChecked(v.id, true, true);
            });
        }
    });
    widget.coverage = true;
};
/**
 * 新建树的数据
 * @param data 数据
 */
export const newTreeNode = (data: any) => {
    let node = {
        editor: true,
        id: data.id,
        isLocked: data.isLocked ? 1 : 0,
        name: data.name ? data.name : data.folderName,
        pid: data.pid ? data.pid : data.folderId ? data.folderId : data.parentFolder,
        show: data.isShow == 1 || data.isShow ? true : false,
        type: data.type,
        icon: data.icon,
    };
    return node;
};
/**
 * 关闭右键菜单
 */
export const closeContextmenu = () => {
    closeContextMenu();
};
/**
 * 处理节点点击
 */
export const handleNodeClick = (data: any) => {
    closeContextMenu();
    if (data.type != "folder") {
        // 标绘
        if (data.type == "xyz") {
            let layer = map.getLayerById(data.id);
            layer.flyTo({ height: 5000 });
        } else {
            let graphic = graphicLayer.getGraphicById(data.id);
            if (graphic && data.show) {
                graphic.flyTo();
            }
        }
    } else {
        // 文件夹
        // if (data.name == "辅助图层" || data.name == "天地图注记" || data.name == "行政区划界线") {
        //     ElMessage.error("该文件夹不能被操作！");
        //     store.tree.setCurrentKey(store.treeDefaultKey, true);
        //     return;
        // }
        store.treeDefaultKey = data.id;
    }
};
/**
 * 处理节点右键
 */
export const nodeContextmenu = (event: any, data: any) => {
    const mars3dTypes = ["swjm", "fztc", "tdtbj", "xzqhjx", "bim", "rgjm", "xyz"];
    if (mars3dTypes.includes(data.mars3dType)) {
        ElMessage.error("该文件夹不能被操作！");
        return;
    }
    // console.log(data);
    // if (data.editor) {
    // console.log(data);
    // 设置右键菜单的位置
    widget.contextMenu.X = event.x;
    widget.contextMenu.Y = event.y;
    widget.contextMenu.name = data.name;
    // 设置右键菜单的类型
    store.rightClickData = data;
    if (data.isLocked == 1) {
        // 文件夹被锁定
        widget.contextMenu.type = "unlock";
    } else if (data.type == "folder") {
        // 文件夹
        if (store.cutCopyData != undefined) {
            widget.contextMenu.type = "paste";
        } else {
            widget.contextMenu.type = "folder";
        }
    } else if (data.type == "xyz") {
        // 金字塔瓦片图层
        widget.contextMenu.type = "xyz";
    } else {
        // 图上绘标
        widget.contextMenu.type = "draw";
    }
    widget.contextMenu.show = true;

    // console.log(store.tree.getNode(store.treeDefaultKey));
    // let defaultNode = store.tree.getNode(store.treeDefaultKey);
    // if (defaultNode.canFocus && defaultNode.expanded) {
    // nextTick(() => {
    //     store.tree.getNode(store.treeDefaultKey).canFocus = false;
    //     store.tree.getNode(store.treeDefaultKey).expanded = false;
    // });
    // }

    // }
};
/**
 * 处理节点复选框
 */
export const checkChange = (data: any) => {
    let handleNode: any = store.tree.getNode(data.id);
    if (data.type == "folder") {
        showRecursion(data, handleNode.checked);
        updateFloaderUpdateState(data, handleNode.checked);
        if (data.mars3dType == "tdtbj" || data.mars3dType == "xzqhjx" || data.mars3dType == "fztc") {
            auxiliaryLayer(data, handleNode.checked);
        }
    } else {
        // 图上绘标
        updateFloaderUpdateState(data, handleNode.checked);
    }
};

// 更新文件夹或标绘显示状态
const updateFloaderUpdateState = (data: any, checked: boolean) => {
    if (data.type == "folder") {
        // 文件夹
        updateFloaderShow({
            folderId: data.id,
            isShow: checked ? 1 : 0,
        }).then((res: any) => {
            data.show = checked;
        });
    } else {
        // 标绘
        updateFloaderShow({
            drawingId: data.id,
            isShow: checked ? 1 : 0,
        }).then((res: any) => {
            data.show = checked;
            if (data.type == "xyz") {
                // 地图金字塔图层显示
                let layer = map.getLayerById(data.id);
                layer.show = checked;
            } else {
                // 地图标绘显示
                let graphic = graphicLayer.getGraphicById(data.id);
                graphic.show = checked;
            }
        });
    }
};
/**
 * 数据显示递归函数
 * @param data
 */
const showRecursion = (data: any, checked: boolean) => {
    data.children.forEach((v: any) => {
        updateFloaderUpdateState(v, checked);
        if (v.children && v.children.length > 0) {
            showRecursion(v, checked);
        }
    });
};
// 辅助图层设置
const auxiliaryLayer = (data: any, checked: boolean) => {
    if (data.mars3dType == "tdtbj" || data.mars3dType == "xzqhjx") {
        if (data.mars3dType == "tdtbj") {
            map.getLayerById(152).show = checked;
        } else {
            map.getLayerById(151).show = checked;
        }
    } else {
        map.getLayerById(152).show = checked;
        map.getLayerById(151).show = checked;
    }
};
/**
 * 新建一级文件夹
 */
export const newFolder = () => {
    ElMessageBox.prompt("请输入文件夹名称", "添加文件夹", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
    }).then(({ value }) => {
        if (value) {
            addFloader({
                parentFolder: null,
                baseId: store.baseId,
                folderName: value,
            }).then((res: any) => {
                // 更新数据
                getCoverage();
                ElMessage.success("添加成功");
            });
        } else {
            ElMessage.error("名称不能为空");
        }
    });
};
/**
 * 关闭上传弹窗
 */
export const handleClose = (data: any) => {
    if (widget.uploadDialog) {
        reselect(data);
    } else {
        widget.uploadDialog = false; // 关闭弹窗
        // console.log(321);
        // widget.drawItemData = undefined;
    }
};
/**
 * 重新选择文件
 */
export const reselect = (data: any) => {
    data.isShowMsg = false;
    data.files = null;
    data.total = 0;
    data.totalSize = 0;
    data.current = 0;
    data.folderName = "";
    data.uploadFilePath = "";
    data.flag = "";
};
/**
 * 上传文件
 */
export const uploadXyzLayer = (e: any, data: any) => {
    data.isShowMsg = true;
    let files = e.target.files;
    let filePath = files[0].webkitRelativePath;
    data.folderName = filePath.split("/")[0];
    // 文件过滤
    data.files = [];
    for (let i = 0; i < files.length; i++) {
        if (files[i].name.split(".")[1] == "png" || files[i].name == "map_report.json") {
            data.totalSize += files[i].size;
            data.files.push(files[i]);
            data.total += 1;
        }
    }
    // 生成文件上传的唯一标识
    data.flag = generateRandomString(20);
};
/**
 * 上传所有文件
 */
export const uploadFilesSubmit = (data: any) => {
    const swNode = store.treeData.find((v: any) => v.mars3dType == "swjm");
    const xyzNode = swNode.children.find((v: any) => v.mars3dType == "xyz");
    let files = data.files;
    // 组合上传参数
    let fromData = new FormData();
    fromData.append("file", files[data.current]); // 文件流
    fromData.append("type", "xyz"); // 文件类型
    // fromData.append("folderId", store.treeDefaultKey); // 文件pid
    fromData.append("folderId", xyzNode.id); // 文件pid
    fromData.append("layerName", data.folderName); // 文件名称
    fromData.append("fileName", files[data.current].name); // 文件临时唯一id
    fromData.append("filePath", files[data.current].webkitRelativePath); // 文件相对路径
    fromData.append("current", data.current + 1); // 文件当前进度
    fromData.append("total", data.total); // 文件总数量
    fromData.append("flag", data.flag); // 文件随机唯一标识
    uploadXyzLayers(fromData).then((res) => {
        data.uploadFilePath = files[data.current].name;
        data.current += 1;
        if (data.current < data.total) {
            uploadFilesSubmit(data);
        } else {
            console.log("上传完成");
            let resData = res.data;
            if (resData) {
                // 添加树菜单数据
                let treeData = {
                    editor: true,
                    id: resData.id,
                    isLocked: 0,
                    name: resData.name,
                    // pid: resData.folderId,
                    pid: xyzNode.id,
                    icon: `${import.meta.env.VITE_BASE_XYZ}/${resData.icon}`,
                    show: true,
                    sort: 0,
                    type: resData.type,
                };
                // store.tree.append(treeData, resData.folderId);
                store.tree.append(treeData, xyzNode.id);
                // 设为树菜单选中状态
                nextTick(() => {
                    store.tree.setCurrentKey(treeData.id);
                    store.tree.setChecked(treeData.id, true);
                });
                // console.log(treeData);
                ElMessageBox.confirm("是否立即加载瓦片图层?", "上传完成", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        handleClose(data);
                        widget.uploadDialog = false;
                        const tileLayer = new mars3d.layer.XyzLayer({
                            url: `${import.meta.env.VITE_BASE_XYZ}/${resData.layerUrl}`,
                            minimumLevel: 12,
                            maximumLevel: 21,
                            rectangle: { xmin: resData.xmin, xmax: resData.xmax, ymin: resData.ymin, ymax: resData.ymax },
                        });
                        map.addLayer(tileLayer);
                        tileLayer.flyTo();
                    })
                    .catch(() => {
                        handleClose(data);
                        widget.uploadDialog = false;
                    });
            }
        }
    });
};
/**
 * 生成随机字符串
 */
export const generateRandomString = (length: number) => {
    let chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let result = "";
    for (let i = length; i > 0; --i) {
        result += chars[Math.floor(Math.random() * chars.length)];
    }
    return result;
};
/**
 * 上移操作
 */
export const moveUp = (data: any) => {
    let tree = store.tree;
    let node = tree.getNode(data.id);
    let parent = node.pid ? tree.getNode(node.pid) : node.parent;
    let index = parent.childNodes.indexOf(node);
    if (index > 0) {
        if (data.type == "folder") {
            // 文件夹上移
            updateFloaderUpFolder({
                id: data.id,
                lastId: parent.childNodes[index - 1].key,
            }).then((res: any) => {
                moveUpRecursion(data);
            });
        } else {
            // 标绘上移
            updateFloaderUp({
                id: data.id,
            }).then((res: any) => {
                moveUpRecursion(data);
            });
        }
    } else {
        ElMessage.error("已经是第一个节点");
    }
};
const moveUpRecursion = (data: any) => {
    ElMessage.success("操作成功");
    let tree = store.tree;
    let node = tree.getNode(data.id);
    let parent = node.pid ? tree.getNode(node.pid) : node.parent;
    let index = parent.childNodes.indexOf(node);
    // 树的节点数据交换
    let temp = parent.childNodes[index - 1]; // 上一个节点
    parent.childNodes[index - 1] = node;
    parent.childNodes[index] = temp;
    tree.setCurrentKey(data.id);
    tree.setChecked(data.id, true);
};
/**
 * 下移操作
 */
export const moveDown = (data: any) => {
    let tree = store.tree;
    let node = tree.getNode(data.id);
    let parent = node.pid ? tree.getNode(node.pid) : node.parent;
    let index = parent.childNodes.indexOf(node);
    if (index < parent.childNodes.length - 1) {
        if (data.type == "folder") {
            // 文件夹下移
            updateFloaderDownFolder({
                id: data.id,
                nextId: parent.childNodes[index + 1].key,
            }).then((res: any) => {
                moveDownRecursion(data);
            });
        } else {
            // 标绘下移
            updateFloaderDown({
                id: data.id,
            }).then((res: any) => {
                moveDownRecursion(data);
            });
        }
    } else {
        ElMessage.error("已经是最后一个节点");
    }
};
const moveDownRecursion = (data: any) => {
    ElMessage.success("操作成功");
    let tree = store.tree;
    let node = tree.getNode(data.id);
    let parent = node.pid ? tree.getNode(node.pid) : node.parent;
    let index = parent.childNodes.indexOf(node);
    // 树的节点数据交换
    let temp = parent.childNodes[index + 1]; // 下一个节点
    parent.childNodes[index + 1] = node;
    parent.childNodes[index] = temp;
    tree.setCurrentKey(data.id);
    tree.setChecked(data.id, true);
};
